package com.dylan.channel.v7;

import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Logger;

public abstract class SingleThreadEventExecutor implements EventExecutor {
    Logger logger = Logger.getLogger(SingleThreadEventExecutor.class.getName());
    Thread thread;

    Queue<Runnable> taskQueue;

    public SingleThreadEventExecutor() {
        taskQueue = new LinkedBlockingQueue<>(1024);
    }

    @Override
    public void execute(Runnable command) {
        if (null == command) {
            logger.warning("任务不能为空!");
            return;
        }
        //将任务添加到任务队列
        if (!addTask(command)) {
            //TODO 执行拒绝策略
        }

        //启动线程完成任务
        startThread();
    }

    private void startThread() {
        if (thread != null) {
            return;
        }
        new Thread(() -> {
            thread = Thread.currentThread();
            SingleThreadEventExecutor.this.run();
        }).start();
    }

    protected abstract void run();

    protected void runAllTask() {
        Runnable task = taskQueue.poll();
        if (Objects.isNull(task)) {
            return;
        }
        for (; ; ) {
            task.run();
            task = taskQueue.poll();
            if (Objects.isNull(task)) {
                return;
            }
        }
    }

    protected boolean hasTask() {
        return !taskQueue.isEmpty();
    }

    private boolean addTask(Runnable command) {
        if (Objects.isNull(command)) {
            logger.warning("任务不能为空!");
            throw new RuntimeException("任务不能为空!");
        }
        return taskQueue.offer(command);
    }

    @Override
    public void shutdownGraceFull() {

    }

    @Override
    public boolean inEventLoop(Thread thread) {
        return this.thread == thread;
    }
}
